<template>
  <el-divider content-position="center">机制</el-divider>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="num" label="次数">
      <template #default="scope">
        <el-input-number v-model="scope.row.num" :min="0" placeholder="次数" class="w100%!" />
      </template>
    </el-table-column>
    <el-table-column prop="money" label="金额">
      <template #default="scope">
        <el-input-number
          v-model="scope.row.money"
          :min="0"
          placeholder="请输入金额"
          class="w100%!"
        />
      </template>
    </el-table-column>
  </el-table>
  <el-divider content-position="center" class="mt15!">购买说明</el-divider>
  <el-input
    v-model="tableData[0].buyExplain"
    maxlength="500"
    :rows="6"
    placeholder="请输入说明"
    show-word-limit
    type="textarea"
  />
  <el-button class="mt6" @click="submitForm" type="primary" :disabled="loading">确 定</el-button>
</template>

<script setup lang="ts">
import * as RecommendSettingApi from '@/api/blind/recommendSetting'

defineOptions({ name: 'RecommendSetting' })

/** 初始化 **/
onMounted(() => {
  getData()
})

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
let formType = ref('create') // 表单的类型：create - 新增；update - 修改

const tableData = ref([
  {
    num: 1,
    money: 0,
    buyExplain: ''
  },
  {
    num: 2,
    money: 0,
    buyExplain: ''
  },
  {
    num: 3,
    money: '0',
    buyExplain: ''
  }
])

/** 查询列表 */
const getData = async () => {
  const data = await RecommendSettingApi.getRecommendSettingPage()

  // 转换数据类型
  const newData = data.list.map((item) => {
    item.num = Number(item.num)
    item.money = Number(item.money)

    return item
  })

  tableData.value = newData

  formType.value = data ? 'update' : 'create'
}

/** 提交表单 */
const submitForm = async () => {
  // 提交请求
  loading.value = true
  try {
    if (formType.value === 'create') {
      await RecommendSettingApi.createRecommendSetting(tableData.value)
      message.success(t('common.createSuccess'))
    } else {
      await RecommendSettingApi.updateRecommendSetting(tableData.value)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    getData()
  } finally {
    loading.value = false
  }
}
</script>
